package ar.fiuba.fallar2.pac_man;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public abstract class AbstractDataMapper implements IDataMapper {
	

	
	@Override
	public IBusinessObject load(int id) {
	
		String sqlQuery = "SELECT * FROM "+getTable()+" WHERE "+getIdColumn()+"="+id;
		
		try {
			ResultSet r = DBManager.getInstance().find(sqlQuery).getResultSet();
			r.next();
			IBusinessObject bo = createBO(r);
			r.close();
			return bo;
		    } catch (SQLException e) {
			 e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	
	public IBusinessObject load(String id) {
		
		String sqlQuery = "SELECT * FROM "+getTable()+" WHERE "+getIdColumn()+"="+id;
		
		try {
			ResultSet r = DBManager.getInstance().find(sqlQuery).getResultSet();
			r.last();
			IBusinessObject bo = createBO(r);
			r.close();
			return bo;
		    } catch (SQLException e) {
			 e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	
	
	@Override
	public void delete(int id) {
		String sql = "DELETE FROM "+ getTable() + " WHERE "+getIdColumn()+"="+ id;
		try {
			DBManager.getInstance().delete(sql);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
	
	public void delete(String id) {
		String sql = "DELETE FROM "+ getTable() + " WHERE "+getIdColumn()+"="+ id;
		try {
			DBManager.getInstance().delete(sql);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
	
	@Override
	public List findAll() {
		try {
			List<IBusinessObject> lista = new ArrayList<IBusinessObject>();
			String sqlQuery = "SELECT * FROM "+getTable();
			ResultSet r = DBManager.getInstance().find(sqlQuery).getResultSet();
			while (r.next()) {
				lista.add(createBO(r));
			}
			r.close();
			return lista;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}


	@Override
	public void save(IBusinessObject obj) {
		try {
			String sql = mapBOInsert(obj);
			System.out.println("SQL GENERADO: "+sql);
			int autoGeneratedId = DBManager.getInstance().save(sql);
			obj.setId(autoGeneratedId);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	@Override
	public void update(IBusinessObject obj) {
		try {
			String sql = mapBOUpdate(obj);
			DBManager.getInstance().update(sql);
			
	   	} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
	protected abstract IBusinessObject createBO(ResultSet r) throws SQLException;
	
	protected abstract String mapBOInsert(IBusinessObject r) throws SQLException;
	
	protected abstract String mapBOUpdate(IBusinessObject r) throws SQLException;
	
	protected abstract String getTable();
	
	protected abstract String getIdColumn();
	
}
